<template>
    <a-modal :keyboard="false" :maskClosable="false" title="工单管理" :open="visible" :width="900" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical">
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="工单类型" v-bind="validateInfos.orderType">
                        <a-radio-group v-model:value="modelRef.orderType" @change="handleOrderTypeChage">
                            <a-radio v-for="(value, key) in typeMap" :key="key" :value="Number(key)">{{ value }}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="工单属性" v-bind="validateInfos.orderProperty">
                        <a-select v-model:value="modelRef.orderProperty" :disabled="modelRef.orderType == 1">
                            <a-select-option v-for="(value, key) in propertyMap" :key="key" :value="Number(key)">{{ value }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="项目名称" v-bind="validateInfos.projectCode">
                        <a-cascader
                            v-model:value="modelRef.projectCode"
                            :options="treeData"
                            :field-names="{
                                children: 'children',
                                label: 'name',
                                value: 'code',
                            }"
                            :show-search="{ filter }"
                            placeholder="选择项目名称"
                            style="width: 100%"
                            @change="handleCascaderChange"
                        />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6" v-if="modelRef.projectCode">
                    <a-form-item label="房间号" v-bind="validateInfos.propertyId">
                        <a-cascader
                            v-model:value="modelRef.propertyId"
                            :options="buildData"
                            :field-names="{
                                children: 'children',
                                label: 'name',
                                value: 'id',
                            }"
                            :show-search="{ filter }"
                            placeholder="选择房间号"
                            style="width: 100%"
                            @change="handleBuildChange"
                        />
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="业主姓名" v-bind="validateInfos.propertyOwnerId">
                        <a-input v-model:value="modelRef.propertyOwner" disabled />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="业主电话" v-bind="validateInfos.propertyPhone">
                        <a-input v-model:value="modelRef.propertyPhone" disabled />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="联系人" v-bind="validateInfos.contactPerson">
                        <a-input v-model:value="modelRef.contactPerson" />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="联系人电话" v-bind="validateInfos.contactPersonPhone">
                        <a-input v-model:value="modelRef.contactPersonPhone" />
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item label="工单分类" v-bind="validateInfos.orderTypeSub">
                        <a-select
                            v-model:value="modelRef.orderTypeSub"
                            style="width: 100%"
                            :options="[
                                {
                                    label: '户内',
                                    value: 0,
                                    disabled: modelRef.publicArea == 1,
                                },
                                {
                                    label: '公区',
                                    value: 1,
                                    disabled: modelRef.publicArea == 0,
                                },
                            ]"
                            @change="handleOrderTypeSubChange"
                        ></a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="6">
                    <a-form-item :label="'详细分类'" v-bind="validateInfos.orderClassifyId">
                        <a-select
                            v-model:value="modelRef.orderClassifyId"
                            style="width: 100%"
                            :disabled="!!modelRef.orderSub"
                            :options="createDictData"
                            :field-names="{ value: 'id', label: 'classifyName' }"
                            placeholder="请先选择工单分类"
                            @change="handleClassifyIdChange"
                        ></a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="12">
                    <a-form-item label="工单来源" v-bind="validateInfos.orderSource">
                        <a-radio-group v-model:value="modelRef.orderSource">
                            <a-radio v-for="item in sourceDataShow" :value="item.value" :key="item.value">{{ item.label }}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="工单描述" v-bind="validateInfos.content">
                        <a-textarea v-model:value="modelRef.content" show-count :maxlength="5000"></a-textarea>
                    </a-form-item>
                </a-col>
                <a-col :xs="24" :sm="24" :md="24">
                    <a-form-item label="工单附件">
                        <custom-upload v-model:fileList="modelRef.fileList" multiple upload-text="上传照片、视频" accept="image/*,video/*" />
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { ShowSearchType } from 'ant-design-vue/es/cascader';
    import type { PropType, Ref } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch, computed } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import { cloneDeep, isEmpty } from 'lodash-es';
    import type { TreeProps } from 'ant-design-vue';
    import { txList } from '@/api/common/proline';
    import { options, statusMap, propertyMap, typeMap } from './common';
    import { queryProjectTree } from '@/api/list/project-list';
    import { getPropertyBasic } from '@/api/list/property-list';
    import { queryBuildTree2Room } from '@/api/list/build';
    import { getList } from '@/api/order/cate';
    import { createOrder } from '@/api/order/mine-list';
    import { dictDataListByDictType } from '@/api/user/dict';
    import { validatePhone } from '@/utils/validate';

    const fieldNames: TreeProps['fieldNames'] = {
        children: 'children',
        title: 'name',
        key: 'code',
    };

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const treeData: Ref<TreeProps['treeData']> = ref([]);
            const buildData = ref<any[]>([]);
            const roleList = ref<any[]>([]);
            const sourceData = ref<any[]>([]);
            const createDictData = ref<any[]>([]);
            const defaultForm = {
                status: 1,
                orderClassifyName: '',
                orderSource: '',
                orderTypeSub: '',
                contactPersonPhone: '',
                contactPerson: '',
                projectCode: '',
                orderType: '',
                orderProperty: '',
                content: '',
                orderClassifyId: '',
                propertyId: '',
                fileList: [],
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));
            const rulesRef = reactive({
                orderClassifyId: [{ required: true, message: '请选择详细分类' }],
                orderType: [{ required: true, message: '请选择工单类型' }],
                orderProperty: [{ required: true, message: '请选择工单属性' }],
                content: [{ required: true, message: '请输入工单描述' }],
                projectCode: [{ required: true, message: '请选择' }],
                contactPerson: [{ required: true, message: '请输入联系人姓名' }],
                contactPersonPhone: [{ required: true, message: '请输入联系人电话' }, { validator: validatePhone }],
                orderTypeSub: [{ required: true, message: '请选择' }],
                orderSource: [{ required: true, message: '请选择' }],
                propertyId: [{ required: true, message: '请选择' }],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);

            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(() => {
                if (props.visible) {
                    txList().then(res => {
                        if (!isEmpty(res.data)) roleList.value = res.data;
                    });

                    dictDataListByDictType({
                        dictType: 'order_ascription',
                    }).then(res => {
                        sourceData.value = res.data;
                    });
                    queryTreeData();

                    if (props.model) {
                        Object.assign(modelRef, props.model, {
                            orderTypeSub: isEmpty(props.model.orderTypeSub) ? [] : props.model.orderTypeSub.split(','),
                        });
                    }
                }
            });

            const sourceDataShow = computed(() => {
                if (modelRef.orderProperty === 0) {
                    // 客户类
                    return sourceData.value.filter(
                        item => item.value == 'visiting' || item.value == 'incoming_call' || item.value == 'xinxi' || item.value == 'manyi' || item.value == 'jituan',
                    );
                } else if (modelRef.orderProperty === 1) {
                    return sourceData.value.filter(item => item.value == 'zc');
                } else {
                    return [];
                }
            });

            const queryBuildTreeData = (codes: any[]) => {
                queryBuildTree2Room(codes[codes.length - 1]).then(build => {
                    buildData.value = isEmpty(build.data) ? [] : build.data;
                });
            };

            const queryTreeData = () => {
                queryProjectTree().then(res => {
                    treeData.value = [res.data as any];
                });
            };

            const handleCascaderChange = (value: any, selectedOptions: any) => {
                const select = selectedOptions[selectedOptions.length - 1];
                modelRef.projectName = select.name;
                if (select.type === 'dept' && select.children.length === 0) {
                    queryBuildTreeData(value);
                } else {
                    message.warning('当前选择无项目');
                    buildData.value = [];
                }
            };

            const handleBuildChange = (value: any, selectedOptions: any) => {
                const select = selectedOptions[selectedOptions.length - 1];
                modelRef.publicArea = select.publicArea;
                modelRef.orderTypeSub = select.publicArea;
                modelRef.orderClassifyId = null;
                handleOrderTypeSubChange(modelRef.orderTypeSub);

                getPropertyBasic(select.id).then(res => {
                    if (!isEmpty(res.data)) {
                        const { owner: propertyOwner, phone: propertyPhone, propertyOwnerId, floorId } = res.data;
                        Object.assign(modelRef, {
                            propertyOwner,
                            propertyOwnerId,
                            propertyPhone,
                            contactPersonPhone: propertyPhone,
                            contactPerson: propertyOwner,
                            floorId,
                        });
                    }
                });
            };

            const handleOrderTypeSubChange = val => {
                getList({
                    orderTypeSub: val,
                    orderType: modelRef.orderType,
                    status: 1,
                }).then(res => {
                    createDictData.value = res.data;
                });
            };

            const handleClassifyIdChange = (val, options) => {
                modelRef.orderProfessionalLine = options.orderProfessionalLine;
                modelRef.orderClassifyName = options.classifyName;
            };

            const handleCancel = () => {
                resetFields();
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));

                modelRef.status = 1;
                emit('cancel');
            };

            const handleSubmit = async () => {
                validate()
                    .then(res => {
                        loading.value = true;

                        createOrder({
                            ...(modelRef as any),
                            projectCode: modelRef.projectCode[modelRef.projectCode.length - 1],
                            propertyId: modelRef.propertyId[modelRef.propertyId.length - 1],
                        })
                            .then(res => {
                                if (res.data) {
                                    message.success('操作成功');
                                    emit('success');
                                    handleCancel();
                                }
                            })
                            .finally(() => {
                                loading.value = false;
                            });
                    })
                    .catch(err => {
                        console.log(err);
                    });
            };

            const handleOrderTypeChage = e => {
                if (e.target.value === 1) {
                    modelRef.orderProperty = 0;
                }
                modelRef.orderTypeSub = '';
                modelRef.orderClassifyId = '';
                createDictData.value = [];
            };

            const filter: ShowSearchType['filter'] = (inputValue, path) => {
                return path.some(option => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
            };
            const filterP: ShowSearchType['filter'] = (inputValue, path) => {
                return path.some(option => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
            };
            return {
                filter,
                filterP,
                sourceDataShow,
                loading,

                modelRef,
                validateInfos,
                resetFields,

                handleSubmit,
                handleCancel,

                initValues,
                fieldNames,
                options,
                statusMap,
                propertyMap,
                typeMap,
                roleList,
                sourceData,
                createDictData,
                isEmpty,

                treeData,
                buildData,
                handleCascaderChange,
                handleBuildChange,
                handleOrderTypeSubChange,
                handleClassifyIdChange,
                handleOrderTypeChage,
            };
        },
    });
</script>
